<script setup>
import api from '../api/seckillgoodsApi.js'
import goodsApi from '../api/goodsApi.js'
import seckillactivityApi from '../api/seckillactivityApi.js'
import { ref, onMounted } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  ElDialog,
  ElNotification,
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElPagination,
  ElTag,
  ElSelect,
  ElOption,
  ElInputNumber
} from 'element-plus'
import { Delete, Edit, Search } from '@element-plus/icons-vue'
import lodash from 'lodash'

// 表格数据
const tableData = ref([])
// 总记录数
const total = ref(0)
// 编辑/新增弹窗显隐
const updateWinVisible = ref(false)
// 表单绑定数据
const obj = ref({})

// 商品列表和秒杀活动列表
const goodsList = ref([])
const activityList = ref([])

// 查询参数（分页 + 搜索条件）
const searchObj = ref({
  pageNum: 1,
  pageSize: 10,
  goodsid: '', // 商品ID搜索
  seckillactivityid: '', // 秒杀活动ID搜索
  status: '', // 状态搜索
  isdel: 0
})

// 获取商品列表
const getGoodsList = async () => {
  try {
    const result = await goodsApi.page({ page: 1, pageSize: 1000, isdel: 0 })
    if (result && result.records) {
      goodsList.value = result.records
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
  }
}

// 获取秒杀活动列表
const getActivityList = async () => {
  try {
    const result = await seckillactivityApi.page({ pageNum: 1, pageSize: 1000, isdel: 0 })
    if (result && result.records) {
      activityList.value = result.records
    }
  } catch (error) {
    console.error('获取秒杀活动列表失败:', error)
  }
}

// 查询数据方法（根据实际API响应结构优化）
const search = async () => {
  try {
    const result = await api.page(searchObj.value)
    console.log('接口完整响应:', result)

    // 根据实际API响应结构处理数据
    if (result && result.records && Array.isArray(result.records)) {
      tableData.value = result.records
      total.value = result.total || 0
      console.log('表格数据:', tableData.value)
      console.log('总记录数:', total.value)
    } else {
      tableData.value = []
      total.value = 0
      console.warn('API响应格式异常:', result)
    }
  } catch (error) {
    ElMessage.error('查询失败，请检查网络或接口！')
    console.error('查询错误详情:', error)
    tableData.value = []
    total.value = 0
  }
}

// 页面挂载时初始化数据
onMounted(async () => {
  await getGoodsList()
  await getActivityList()
  await search()
})

// 编辑功能（深拷贝避免原数据被修改）
const handleEdit = (index, row) => {
  obj.value = lodash.cloneDeep(row)
  updateWinVisible.value = true
}

// 删除功能（带二次确认）
const handleDelete = async (index, row) => {
  ElMessageBox.confirm(
      '确定删除该秒杀商品吗？删除后不可恢复！',
      '危险操作',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'danger'
      }
  )
      .then(async () => {
        try {
          await api.delete(row.id)
          ElMessage.success('删除成功！')
          await search() // 重新加载当前页
        } catch (error) {
          ElMessage.error('删除失败：' + (error.response?.data?.msg || '接口异常'))
          console.error('删除错误详情:', error)
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
}

// 保存编辑/新增（区分新增和编辑）
const handleSave = async () => {
  try {
    if (obj.value.id) {
      // 编辑操作
      await api.update(obj.value)
      ElMessage.success('更新成功！')
    } else {
      // 新增操作
      await api.add(obj.value)
      ElMessage.success('新增成功！')
    }
    updateWinVisible.value = false
    await search() // 刷新表格
    obj.value = {} // 清空表单
  } catch (error) {
    ElMessage.error('操作失败：' + (error.response?.data?.msg || '接口异常'))
    console.error('保存错误详情:', error)
  }
}

// 取消编辑（清空表单 + 关闭弹窗）
const handleCancel = () => {
  updateWinVisible.value = false
  obj.value = {}
}

// 新增秒杀商品（清空表单 + 打开弹窗）
const handleAdd = () => {
  obj.value = {
    status: 1 // 默认状态为启用
  }
  updateWinVisible.value = true
}

// 分页大小改变（如从10条/页 → 20条/页）
const handleSizeChange = async (newSize) => {
  searchObj.value.pageSize = newSize
  searchObj.value.pageNum = 1 // 重置到第一页
  await search()
}

// 当前页改变（如从第1页 → 第2页）
const handleCurrentChange = async (newPage) => {
  searchObj.value.pageNum = newPage
  await search()
}

// 搜索按钮（带分页重置）
const handleSearch = async () => {
  searchObj.value.pageNum = 1 // 搜索时默认查第一页
  await search()
}

// 重置搜索条件（清空搜索框 + 分页重置）
const handleReset = async () => {
  searchObj.value = {
    pageNum: 1,
    pageSize: 10,
    goodsid: '',
    seckillactivityid: '',
    status: '',
    isdel: 0
  }
  await search()
}

// 时间格式化
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  // 格式化为：年-月-日 时:分:秒
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
}

// 获取商品名称
const getGoodsName = (goodsid) => {
  const goods = goodsList.value.find(g => g.id === goodsid)
  return goods ? goods.name : '未知商品'
}

// 获取秒杀活动名称
const getActivityName = (activityid) => {
  const activity = activityList.value.find(a => a.id === activityid)
  return activity ? activity.name : '未知活动'
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '禁用'
    case 1: return '启用'
    default: return '未知'
  }
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'danger'
    case 1: return 'success'
    default: return 'info'
  }
}

// 通知组件
const showNotification = (options) => {
  const {type, message} = options
  if (!type || !message) {
    console.warn('通知类型和消息内容不能为空')
    return
  }

  ElNotification({
    title: type === 'success' ? '成功' :
        type === 'error' ? '错误' :
            type === 'warning' ? '警告' : '信息',
    message: message,
    type: type,
    duration: 2000
  })
}
</script>

<template>
  <div class="page-container">
    <!-- 搜索 + 按钮区域 -->
    <div class="top-bar">
      <!-- 搜索区域 -->
      <el-form :model="searchObj" inline class="search-form">
        <el-form-item label="商品：">
          <el-select
              v-model="searchObj.goodsid"
              placeholder="请选择商品"
              clearable
              style="width: 200px;"
              filterable
          >
            <el-option
                v-for="goods in goodsList"
                :key="goods.id"
                :label="goods.name"
                :value="goods.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="秒杀活动：">
          <el-select
              v-model="searchObj.seckillactivityid"
              placeholder="请选择秒杀活动"
              clearable
              style="width: 200px;"
              filterable
          >
            <el-option
                v-for="activity in activityList"
                :key="activity.id"
                :label="activity.name"
                :value="activity.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select
              v-model="searchObj.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px;"
          >
            <el-option label="全部" :value="''"></el-option>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" circle @click="handleSearch" />
          <el-button type="default" :icon="Delete" circle @click="handleReset" />
        </el-form-item>
      </el-form>

      <!-- 新增按钮（右对齐） -->
      <el-button type="success" round @click="handleAdd" class="add-btn">新增秒杀商品</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
          :data="tableData"
          class="seckillgoods-table"
          border
          stripe
          empty-text="暂无数据"
          v-loading="false"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
      >
        <el-table-column fixed prop="id" label="ID" width="80" align="center" />
        <el-table-column label="商品名称" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            {{ getGoodsName(scope.row.goodsid) }}
          </template>
        </el-table-column>
        <el-table-column label="秒杀活动" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            {{ getActivityName(scope.row.seckillactivityid) }}
          </template>
        </el-table-column>
        <el-table-column prop="seckillprice" label="秒杀价格" width="120" align="center">
          <template #default="scope">
            ¥{{ scope.row.seckillprice }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" align="center" />
        <el-table-column label="开始时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.starttime) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.endtime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createtime) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.updatetime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-button
                type="primary"
                :icon="Edit"
                circle
                size="small"
                @click="handleEdit(scope.$index, scope.row)"
                title="编辑"
            />
            <el-button
                type="danger"
                :icon="Delete"
                circle
                size="small"
                @click="handleDelete(scope.$index, scope.row)"
                title="删除"
                style="margin-left: 8px;"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="searchObj.pageNum"
          v-model:page-size="searchObj.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑/新增弹窗 -->
    <el-dialog
        v-model="updateWinVisible"
        :title="obj.id ? '编辑秒杀商品' : '新增秒杀商品'"
        width="600px"
        :before-close="handleCancel"
    >
      <el-form :model="obj" label-width="120px" style="margin-top: 20px;">
        <el-form-item label="商品" prop="goodsid">
          <el-select v-model="obj.goodsid" placeholder="请选择商品" style="width: 100%" filterable>
            <el-option
                v-for="goods in goodsList"
                :key="goods.id"
                :label="goods.name"
                :value="goods.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="秒杀活动" prop="seckillactivityid">
          <el-select v-model="obj.seckillactivityid" placeholder="请选择秒杀活动" style="width: 100%" filterable>
            <el-option
                v-for="activity in activityList"
                :key="activity.id"
                :label="activity.name"
                :value="activity.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="秒杀价格" prop="seckillprice">
          <el-input-number
              v-model="obj.seckillprice"
              :min="0"
              :precision="2"
              placeholder="请输入秒杀价格"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input-number
              v-model="obj.stock"
              :min="0"
              placeholder="请输入库存数量"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="starttime">
          <el-date-picker
              v-model="obj.starttime"
              type="datetime"
              placeholder="请选择开始时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:00"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endtime">
          <el-date-picker
              v-model="obj.endtime"
              type="datetime"
              placeholder="请选择结束时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:00"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="obj.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="启用" :value="1"/>
            <el-option label="禁用" :value="0"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 页面整体容器 */
.page-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

/* 顶部搜索 + 按钮栏 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 搜索表单 */
.search-form {
  display: flex;
  align-items: center;
}

/* 新增按钮 */
.add-btn {
  padding: 8px 20px; /* 缩小按钮内边距，避免过宽 */
  font-size: 14px;
}

/* 表格容器 */
.table-container {
  width: 100%;
  overflow-x: auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* 表格样式 */
.seckillgoods-table {
  width: 100%;
  min-width: 1200px;
}

/* 表格行悬停 */
:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 表格头部 */
:deep(.el-table th.el-table__cell) {
  padding: 12px 0;
  font-size: 14px;
}

/* 表格单元格 */
:deep(.el-table td.el-table__cell) {
  padding: 10px 0;
}

/* 分页容器 */
.pagination-container {
  text-align: center;
  margin-top: 20px;
}

/* 按钮间距 */
.el-button + .el-button {
  margin-left: 10px;
}

/* 弹窗内容滚动 */
:deep(.el-dialog__body) {
  max-height: 60vh;
  overflow-y: auto;
}

/* 响应式适配（小屏幕） */
@media (max-width: 768px) {
  .page-container {
    padding: 10px;
  }
  .top-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px; /* 按钮与搜索框间距 */
  }
  .search-form {
    width: 100%;
  }
  .add-btn {
    align-self: flex-start; /* 按钮左对齐 */
  }
  .table-container {
    margin: 10px 0;
    border-radius: 4px;
  }
  :deep(.el-table th.el-table__cell),
  :deep(.el-table td.el-table__cell) {
    padding: 8px 0;
    font-size: 12px;
  }
}
</style>